/*
 * @(#)WebSocket.java 0.1.0 01/20/2012
 * Copyright(c) CS5321
 * Baylor University, Waco, Texas, U.S.A
 * All Rights Reserved.
 */

package edu.baylor.websocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * WebSocket is implemented according to RFC6544
 * @version 1.0.0 01/20/2012
 * @author Yanqing Liu
 *
 */
public class WebSocket implements IWebSocket {
    
    private WebSocketFramer framer; // Build frame and get byte array 
    private InputStream in;
    private OutputStream out;
    private Socket clntSock;
    
    /**
     * Class WebSocket constructor method
     * @param clnt the tcp socket from which WebSocketServer send and receive message;
     */
    public WebSocket(Socket clntSocket) {
        this.clntSock = clntSocket;
        try {
            this.in = clntSocket.getInputStream();
            this.out = clntSocket.getOutputStream();
        } catch(Exception e) {
                System.out.println("There is a error in WebSocketServer!");
        }
        this.framer = new WebSocketFramer(in,out);
    }
    
    @Override
    public IWSMessage receiveMessage() throws WSException {
        WSMessage msg;
        
        try {
            msg = framer.nextMsg();
        } catch (Exception e) {
            throw new WSException("receive Message");
        }

        return(msg);
    }
    
    @Override
    public void sendMessage(IWSMessage msg) throws WSException {
        try {
            framer.frameMsg(msg);
        } catch (Exception e) {
            throw new WSException("error in sendMessage");
        }
    }
    
    @Override
    public void closeConnection() throws WSException {
        try {
            framer.sendClose();
            clntSock.close();
        } catch (IOException e) {
                throw new WSException("closeConnection error!");
        } finally {
            try {
                clntSock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    @Override
    public boolean isClosed() {
        return (clntSock.isClosed());
    }

    @Override
    public boolean hasNextMessage() {
        // TODO Have no idea how to implement and the necessity, need discussion.
        return false;
    }
}


	
